package edu.clarkson.ee368.spring2012.coreservices;

import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class AccountDAOBean implements AccountDAO {
	
	@PersistenceContext
	private EntityManager em;
	
	public AccountDAOBean() {
	}
	
	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public Account getAccountFromId(long accountId) {
		return em.find(AccountImpl.class, accountId);
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public long createAccount(String username, String password)
			throws AccountAlreadyExistsException {
		if (getAccountFromUserPass(username, password) != null) {
			throw new AccountAlreadyExistsException();
		}
		else {
			Account account = new AccountImpl();
			account.setUserName(username);
			account.setPassword(password);
			em.persist(account);
			em.flush();
			return account.getId();
		}
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public Account getAccountFromUserPass(String username, String password) {
		Query query = em.createNamedQuery("findWithUserAndPassword");
		query.setMaxResults(1);
		query.setParameter("username", username);
		query.setParameter("password", password);
		List<?> results = query.getResultList();
		if (results.isEmpty()) {
			return null;
		}
		else {
			return (Account) results.get(0);
		}
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public Account getAccountFromUser(String targetUserName) {
		Query query = em.createNamedQuery("findWithUser");
		query.setMaxResults(1);
		query.setParameter("username", targetUserName);
		List<?> results = query.getResultList();
		if (results.isEmpty()) {
			return null;
		}
		else {
			return (Account) results.get(0);
		}
	}

}
